package com.demo.simpletestapp.ai

import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.demo.simpletestapp.R
import com.demo.simpletestapp.databinding.ActivityAiBinding
import com.example.base_lib.BaseActivity
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit


class AiActivity : BaseActivity<ActivityAiBinding>() {
    val client_secret = "WhSKK0W6W4RxK9kozOtBgagba07V5Yam"
    val client_id = "lbxMAPGFT8sTxjSdAF1i8Qd5"
    val time = 2L

    val HTTP_CLIENT: OkHttpClient = OkHttpClient()
        .newBuilder()
        .connectTimeout(time, TimeUnit.MINUTES) // 设置连接超时时间为time
        .readTimeout(time, TimeUnit.MINUTES)    // 设置读取超时时间为time
        .writeTimeout(time, TimeUnit.MINUTES)   // 设置写入超时时间为time
        .build()
    val gson by lazy { Gson() }
    lateinit var loginResponse: AiLoginResponse

    /**
     * 聊天内容
     */
    private val messageList = mutableListOf<TalkDataResponse>()
    val adapter by lazy { MyAdapter(messageList) }


    private fun connectAiService() {
        val mediaType: MediaType = MediaType.parse("application/json")!!
        val body: RequestBody = RequestBody.create(mediaType, "")
        val request: Request = Request.Builder()
            .url("https://aip.baidubce.com/oauth/2.0/token?client_id=$client_id&client_secret=$client_secret&grant_type=client_credentials")
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .build()
        HTTP_CLIENT.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                if (e is SocketTimeoutException) {
                    // 处理超时错误
                    Toast.makeText(this@AiActivity, "网络超时了", Toast.LENGTH_SHORT).show()
                    Log.e("OkHttp", "超时错误：${e.message}")
                } else {
                    // 处理其他网络请求失败情况
                    Toast.makeText(this@AiActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                    Log.e("OkHttp", "网络请求失败：${e.message}")
                }
            }

            override fun onResponse(call: Call, response: Response) {
                response.body()?.let {
                    val string = it.string()
                    loginResponse =
                        gson.fromJson(string, AiLoginResponse::class.java)
                    println("refresh_token=${loginResponse.refresh_token}")
//            println(string)
                }
            }

        })
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_ai
    }

    override fun onInit() {
        initRecyclerView()
        login()
        binding.btnSend.setOnClickListener {
            val toString = binding.edInput.text.toString()
            if (toString.isNotEmpty()) {
                MainScope().launch(IO) {
                    sendMessage(toString)
                }
                binding.edInput.setText("")
            } else {
                Toast.makeText(this, "请输入发送内容", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun initRecyclerView() {
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter
    }

    /**
     * 初始化获取数据 true-是
     */
    private var isInit = true

    private suspend fun sendMessage(content: String) {
        val mediaType = MediaType.parse("application/json")
        val body = RequestBody.create(
            mediaType,
            "{\"messages\":${getMessageJson(content)},\"disable_search\":false,\"enable_citation\":false}"
        )
        val request: Request = Request.Builder()
            .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + getAccessToken())
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build()
        val response = HTTP_CLIENT.newCall(request).execute()
        response.body()?.let {
            val string = it.string()
            val fromJson = gson.fromJson(string, ChatCompletionData::class.java)
            val result = fromJson.result
            println("返回的数据：$result")
            val talkDataResponse = TalkDataResponse("assistant", result)
            messageList.add(talkDataResponse)
            if (isInit) {
                binding.recyclerView.post {
                    adapter.notifyDataSetChanged()
                    binding.recyclerView.scrollToPosition(messageList.size - 1)
                }
                isInit = false
            } else {
                binding.recyclerView.post {
                    adapter.notifyItemInserted(messageList.size - 1)
                    binding.recyclerView.smoothScrollToPosition(messageList.size - 1)
                }
            }
        }
    }

    /**
     * 获取发送消息的json字符串
     */
    private suspend fun getMessageJson(content: String): String {
        return withContext(Main) {
            println("输入框内容：$content")
            val element = TalkDataResponse("user", content)
            messageList.add(element)
            println("messageList的内容 ${messageList.size}")
            messageList.forEach {
                println(it.toString())
            }
            delay(100)
//            adapter.notifyItemInserted(messageList.size-1)
            adapter.notifyDataSetChanged()
            binding.recyclerView.smoothScrollToPosition(adapter.itemCount)
            val toJson = gson.toJson(messageList)
            println("发送的json信息： $toJson")
            return@withContext toJson
        }
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    @Throws(IOException::class)
    fun getAccessToken(): String? {
        val mediaType = MediaType.parse("application/x-www-form-urlencoded")
        val body = RequestBody.create(
            mediaType, "grant_type=client_credentials&client_id=" + client_id
                    + "&client_secret=" + client_secret
        )
        val request: Request = Request.Builder()
            .url("https://aip.baidubce.com/oauth/2.0/token")
            .method("POST", body)
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build()
        val response = HTTP_CLIENT.newCall(request).execute()
        return JSONObject(response.body()!!.string()).getString("access_token")
    }


    private fun login() {
        MainScope().launch(IO) {
            connectAiService()
        }
    }


}